<template>
  <view :data-theme="globPrimary" class="exam-share">
    <u-navbar
      is-fixed
      immersive
      :border-bottom="false"
      :background="{ background: 'transparent' }"
      :custom-back="onBack"
    ></u-navbar>
    <view class="share-header">
      <view class="title">试卷验证</view>
      <view class="info">进入考试需进行验证，验证成功即可进入考试</view>
    </view>

    <view class="share-body">
      <view v-if="steps == 1" class="user-wrap">
        <u-icon name="error-circle-fill" color="#DCDFE6" size="98"></u-icon>
        <view class="text">很抱歉！签名错误，不能进行考试</view>
        <edu-button type="primary" size="medium" @click="onBack">返回首页</edu-button>
      </view>

      <view v-else-if="steps == 3" class="user-wrap">
        <u-icon name="error-circle-fill" color="#DCDFE6" size="98"></u-icon>
        <view class="text">很抱歉！您未在白名单上，不能进行考试</view>
        <edu-button type="primary" size="medium" @click="onBack">返回首页</edu-button>
      </view>

      <view v-else-if="steps == 4" class="verify-wrap">
        <view class="title">验证码</view>
        <view class="input"><u-input v-model="value" placeholder="输入试卷验证码" border /></view>
        <edu-button
          type="primary"
          size="medium"
          :disabled="codeBtnDisabled"
          @click="handleSubmitForm"
          >立即验证</edu-button
        >
      </view>

      <view v-else-if="steps == 5" class="face-wrap">
        <view class="face-img">
          <u-image
            :width="488"
            :height="488"
            src="@/static/images/face_verify_placeholder.png"
          ></u-image>
        </view>
        <edu-button type="primary" size="medium" @click="openFace">人脸验证</edu-button>
      </view>

      <view v-else-if="steps == 6" class="user-wrap">
        <edu-button type="primary" size="medium" @click="toTopic">去考试</edu-button>
      </view>
    </view>

    <!-- 人脸 -->
    <edu-face ref="refFaceVerify" @confirm="onFaceVerifyConfirm"></edu-face>
  </view>
</template>

<script>
import { mapGetters } from 'vuex'
import dokey from '@/utils/dokey.js'
import SparkMD5 from '@/utils/spark-md5.js'
export default {
  data() {
    return {
      steps: 0, // 步骤
      value: '', // 验证码
      faceVisible: false, // 人脸验证框
      routeQueryData: {},
    }
  },
  computed: {
    ...mapGetters({
      globPrimary: 'designSetting/getGlobTheme',
      globPrimaryColor: 'designSetting/getGlobThemeColor',
      userInfo: 'user/getUserInfo',
      isLogin: 'user/getHasLogin',
    }),
    faceStatus() {
      return this.userInfo.face_verified
    },
    codeBtnDisabled() {
      return this.$u.test.empty(this.value)
    },
  },
  onLoad(option) {
    if (!this.$u.test.empty(option)) {
      this.routeQueryData = option
      this.init()
    }
  },
  onShow() {
    if (!this.$u.test.empty(this.routeQueryData)) {
      this.init()
    }
  },
  methods: {
    init() {
      const userInfo = this.userInfo
      const query = this.routeQueryData
      const array = ['id', 'n', 'f', 'u', 'c', 'st', 'et']
      const params = this.getParamsData(query, array) // 接口验证参数
      const sign = dokey.secretdate(params, query.sg_t, query.sg_n) // 签名
      // 第一步 验证签名
      if (sign['E-APP-SIGN'] != query.sg_s) {
        this.steps = 1
      }
      // 第二步 未登录
      else if (!this.isLogin) {
        this.$edu.judgeLogin()
      }
      // 第三步 白名单
      else if (this.$edu.test.isDef(params.u) && !params.u.includes(userInfo.id)) {
        this.steps = 3
      }
      // 第四步 验证码
      else if (this.$edu.test.isDef(params.c)) {
        this.steps = 4
      }
      // 第五步 人脸
      else if (this.$edu.test.isDef(params.f) && params.f == 1) {
        this.steps = 5
        this.openFace()
      } else {
        this.steps = 6
      }
    },
    getParamsData(query, array) {
      let params = {} // 接口验证参数
      for (let i in query) {
        array.forEach((k) => {
          if (i == k) params[i] = query[i]
        })
      }
      return params
    },
    // 验证码
    handleSubmitForm() {
      const params = this.routeQueryData
      const code = SparkMD5.hash(this.value)
      if (params.c === code) {
        // 验证成功是否需要人脸
        if (this.$edu.test.isDef(params.f) && params.f == 1) {
          this.steps = 5
          this.openFace()
        } else {
          this.toTopic()
        }
      } else {
        this.$u.toast('验证码错误')
      }
    },
    // 打开人脸
    openFace() {
      this.$refs.refFaceVerify.onFaceMessage()
    },
    // 提交人脸验证
    onFaceVerifyConfirm(file) {
      const query = this.routeQueryData
      uploadFile('/user/tencent/face/person/verify', file, {
        scene_key: 'exam',
        scene_id: query.id,
        scene_type: 1,
      })
        .then((res) => {
          this.$u.toast(res.msg)
          this.$refs.refFaceVerify.onClose()
          this.toTopic()
        })
        .catch((err) => {
          this.$u.toast(err.msg)
          this.$refs.refFaceVerify.resetPhoto()
        })
    },
    async toTopic() {
      this.$u.debounce(
        async () => {
          const query = this.routeQueryData
          const exam = await this.$edu.api
            .getPaperBaser({ paper_id: query.id })
            .then((res) => res.data)
          const timestamp = new Date().getTime() // 时间戳
          const lowerBound = Math.round(query.st) || null // 下限时间戳
          const upperBound = Math.round(query.et) || null // 上限时间戳
          //  n 可考次数 screen_cut 已考试次数
          if (
            this.$edu.test.isDef(query.n) &&
            Number(query.n) > 0 &&
            query.n <= exam.examination_answer_count
          ) {
            this.$u.toast('考试次数已用完')
          } else if (lowerBound && lowerBound > timestamp) {
            this.$u.toast('暂未开放')
          } else if (upperBound && upperBound < timestamp) {
            this.$u.toast('暂未开放')
          } else {
            this.$u.route('pageFound/exam/paper/topic', {
              id: query.id,
              s: 1,
            })
          }
        },
        2000,
        true
      )
    },
    // 返回上一页
    onBack() {
      this.$u.route({ type: 'switchTab', url: 'pages/index/index' })
    },
  },
}
</script>

<style lang="scss" scoped>
.exam-share {
  min-height: 100vh;
  background: #ffffff;
  .share-header {
    height: 398rpx;
    background-image: url('@/pageFound/static/images/examverify_top_bg.png');
    background-size: 100%;
    background-repeat: no-repeat;
    display: flex;
    flex-direction: column;
    justify-content: flex-end;
    padding-bottom: 100rpx;
    padding-left: 95rpx;
    .title {
      font-size: 36rpx;
      font-weight: 600;
      color: $edu-main-color;
    }
    .info {
      margin-top: 16rpx;
      font-size: 24rpx;
      font-weight: 400;
      color: $edu-tips-color;
    }
  }
  .share-body {
    margin-top: 100rpx;
    .user-wrap {
      padding: 0 120rpx;
      display: flex;
      flex-direction: column;
      align-items: center;
      .text {
        margin-top: 40rpx;
        margin-bottom: 72rpx;
        font-size: 26rpx;
        font-weight: 400;
        color: $edu-main-color;
        line-height: 40rpx;
        text-align: center;
      }
    }
    .verify-wrap {
      padding: 0 95rpx;
      .title {
        font-size: 28rpx;
        font-weight: 500;
        color: $edu-main-color;
        margin-bottom: 32rpx;
      }
      .input {
        margin-bottom: 72rpx;
      }
    }
    .face-wrap {
      padding: 0 120rpx;
      display: flex;
      flex-direction: column;
      align-items: center;
      .face-img {
        margin-bottom: 72rpx;
      }
    }
  }
}
</style>
